package freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/21.
 *
 * @author zlf
 */
public class demo1 {

    @Test
    public void test1() throws IOException, TemplateException {
        //创建一个模版对象
        Template t = new Template(null, new StringReader("用户名：${user};URL：    ${url};姓名： 　${name}"), null);
        //创建插值的Map
        Map map = new HashMap();
        map.put("user", "lavasoft");
        map.put("url", "http://www.baidu.com/");
        map.put("name", "百度");
        //执行插值，并输出到指定的输出流中
        t.process(map, new OutputStreamWriter(System.out));
    }

    @Test
    public void test(){
        Configuration config=new Configuration(Configuration.VERSION_2_3_0);

        try {
            config.setDirectoryForTemplateLoading(new File("D:\\IdeaProjects\\web-template\\test\\module-freemarker\\src\\main\\resources"));
//            TemplateLoader loader=null;
//            config.setTemplateLoader(loader);
            Map map=new HashMap<>();
            map.put("user", "lavasoft");
            map.put("url", "http://www.baidu.com/");
            map.put("name", "百度");
            Template template=config.getTemplate("template.ftl");
            template.process(map, new OutputStreamWriter(System.out));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


    }
    @Test
    public void testFreeMarkerword(){
        Configuration config=new Configuration(Configuration.VERSION_2_3_0);

        try {
            File file=new File("C:\\Users\\Administrator\\Desktop");
            config.setDirectoryForTemplateLoading(file);
//            TemplateLoader loader=null;
//            config.setTemplateLoader(loader);
            Map map=new HashMap<>();
            map.put("sss", "lavasoft");
            int n=10;
            map.put("count",5+n); //行数
            List<Map<String,Object>> list=new ArrayList<>();
            for(int i=0;i<n;i++){
                Map<String,Object> m=new HashMap<>();
                m.put("name","aa"+i);
                m.put("age",String.valueOf(i));
                m.put("log","log"+i);
                m.put("index",i+2);
                list.add(m);
            }
            map.put("table",list);
            Template template=config.getTemplate("test.xml");
            File f=new File(file,"test1.xml");
            template.process(map, new OutputStreamWriter(new FileOutputStream(f)));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }




}
